#include "PerformanceTimer.h"
#include <iostream>
#include <iomanip>

void Timer::start() {
    start_time_ = std::chrono::high_resolution_clock::now();
}

void Timer::end() {
    auto end_time = std::chrono::high_resolution_clock::now();
    last_duration_ = std::chrono::duration<double, std::milli>(end_time - start_time_).count();

    total_time_ += last_duration_;
    if (last_duration_ < min_time_) min_time_ = last_duration_;
    if (last_duration_ > max_time_) max_time_ = last_duration_;
    ++count_;
}

void Timer::printSummary(const std::string& name) const {
    if (count_ == 0) {
        std::cout << "无统计数据" << std::endl;
        return;
    }

    double avg = total_time_ / count_;
    double fps = 1000.0 / avg;

    std::cout << std::fixed << std::setprecision(6);
    std::cout << "Timer Name: " << name << std::endl;
    std::cout << "Count     : " << count_ << std::endl;
    std::cout << "Min       : " << min_time_ << " ms" << std::endl;
    std::cout << "Max       : " << max_time_ << " ms" << std::endl;
    std::cout << "Avg       : " << avg << " ms" << std::endl;
    std::cout << "FPS       : " << fps << " FPS" << std::endl;
    std::cout << "Last      : " << last_duration_ << " ms" << std::endl;  // 新增输出
    std::cout << "--------------------" << std::endl;
}

double Timer::getLastDuration() const {
    return last_duration_;
}

void TimerManager::start(const std::string& name) {
    timers_[name].start();
}

void TimerManager::end(const std::string& name) {
    timers_[name].end();
}

void TimerManager::printAllSummaries() const {
    std::cout << "\n性能统计信息:\n";
    std::cout << "=============================================" << std::endl;
    for (const auto& [name, timer] : timers_) {
        timer.printSummary(name);
    }
}

double TimerManager::getLastDuration(const std::string& name) const {
    auto it = timers_.find(name);
    if (it != timers_.end()) {
        return it->second.getLastDuration();
    }
    return 0.0;  // 如果找不到计时器，返回0
}

TimerManager& TimerManager::getInstance() {
    static TimerManager instance;
    return instance;
}